﻿using System;
using System.Device.Location;
using System.IO;
using System.IO.IsolatedStorage;
using Caliburn.Micro;
using Ninject;
using Spotted.Core;
using Spotted.Data.Repositories;

namespace Spotted.ViewModels
{
    public class GatewayPageViewModel : ViewModelBase
    {
        private readonly INavigationService _navigationService;
        private readonly GeoCoordinateWatcher _coordinateWatcher;

        [Inject]
        public IPlacesRepository PlacesRepository { get; set; }

        [Inject]
        public GatewayPageViewModel(INavigationService navigationService) : base(navigationService)
        {
            // assign helpers
            _navigationService = navigationService;
            _coordinateWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High) { MovementThreshold = 20 };

            if (HasValidLogin())
            {
                Initialize();
            }
            else
            {
                GoToLogin();
            }
        }

        private bool HasValidLogin()
        {
            using (var userInformation = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!userInformation.FileExists(Constants.SpottedLoginInformationFileName))
                    return false;

                return true;
            }
        }

        private void Initialize()
        {
            _coordinateWatcher.PositionChanged += coordinateWatcher_PositionChanged;
            _coordinateWatcher.Start();
        }

        private void GoToLogin()
        {
            _navigationService.UriFor<LoginPageViewModel>().Navigate();
        }

        private void coordinateWatcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            // stop the gps
            _coordinateWatcher.Stop();
            
            // load the places for this area
            PlacesRepository.FindNearbyPlacesCompleted += PlacesRepository_FindNearbyPlacesCompleted;
            var gc = new GeoCoordinate(42.0058, -87.6612);
            PlacesRepository.FindNearbyPlaces(gc.Latitude, gc.Longitude);
        }

        private void PlacesRepository_FindNearbyPlacesCompleted(object sender, EventArgs e)
        {
            var gc = new GeoCoordinate(42.0058, -87.6612);
            double latitude = gc.Latitude;
            double longitude = gc.Longitude;

            _navigationService.UriFor<MainPageViewModel>()
                .WithParam(mv => mv.CenterLatitude, latitude)
                .WithParam(mv => mv.CenterLongitude, longitude)
                .Navigate();
        }
    }
}
